package com.ruoyi.system.service.impl;

import java.util.List;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.StudentInfoMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.domain.StudentInfo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.IStudentInfoService;

/**
 * 学生信息Service业务层处理
 *
 * @author ltr
 * @date 2024-10-21
 */
@Service
public class StudentInfoServiceImpl implements IStudentInfoService
{
    private static final Logger log = LoggerFactory.getLogger(StudentInfoServiceImpl.class);

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    protected Validator validator;

    // ==================== 原有功能 ====================

    /**
     * 查询学生信息
     *
     * @param studentId 学生信息主键
     * @return 学生信息
     */
    @Override
    public StudentInfo selectStudentInfoByStudentId(Long studentId)
    {
        StudentInfo studentInfo = studentInfoMapper.selectStudentInfoByStudentId(studentId);
        // 填充nickName字段（从sys_user表获取）
        if (studentInfo != null && studentInfo.getUserId() != null)
        {
            SysUser user = userMapper.selectUserById(studentInfo.getUserId());
            if (user != null)
            {
                studentInfo.setNickName(user.getNickName());
            }
        }
        return studentInfo;
    }

    /**
     * 根据用户ID查询学生信息
     *
     * @param userId 用户ID
     * @return 学生信息
     */
    @Override
    public StudentInfo selectStudentInfoByUserId(Long userId)
    {
        return studentInfoMapper.selectStudentInfoByUserId(userId);
    }

    /**
     * 查询学生信息列表
     *
     * @param studentInfo 学生信息
     * @return 学生信息
     */
    @Override
    public List<StudentInfo> selectStudentInfoList(StudentInfo studentInfo)
    {
        List<StudentInfo> list = studentInfoMapper.selectStudentInfoList(studentInfo);
        // 填充nickName字段（从sys_user表获取）
        for (StudentInfo info : list)
        {
            if (info.getUserId() != null)
            {
                SysUser user = userMapper.selectUserById(info.getUserId());
                if (user != null)
                {
                    info.setNickName(user.getNickName());
                }
            }
        }
        return list;
    }

    /**
     * 新增学生信息
     *
     * @param studentInfo 学生信息
     * @return 结果
     */
    @Override
    public int insertStudentInfo(StudentInfo studentInfo)
    {
        studentInfo.setCreateTime(DateUtils.getNowDate());
        return studentInfoMapper.insertStudentInfo(studentInfo);
    }

    /**
     * 修改学生信息
     *
     * @param studentInfo 学生信息
     * @return 结果
     */
    @Override
    public int updateStudentInfo(StudentInfo studentInfo)
    {
        studentInfo.setUpdateTime(DateUtils.getNowDate());

        // 同步更新系统用户的昵称和邮箱
        if (studentInfo.getUserId() != null)
        {
            SysUser user = new SysUser();
            user.setUserId(studentInfo.getUserId());

            // 更新昵称
            if (StringUtils.isNotEmpty(studentInfo.getNickName()))
            {
                user.setNickName(studentInfo.getNickName());
            }

            // 更新邮箱
            if (StringUtils.isNotEmpty(studentInfo.getEmail()))
            {
                user.setEmail(studentInfo.getEmail());
            }

            userMapper.updateUser(user);
        }

        return studentInfoMapper.updateStudentInfo(studentInfo);
    }

    /**
     * 批量删除学生信息
     *
     * @param studentIds 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStudentInfoByStudentIds(Long[] studentIds)
    {
        // 删除学生信息前，先删除关联的系统用户账号
        for (Long studentId : studentIds)
        {
            StudentInfo studentInfo = studentInfoMapper.selectStudentInfoByStudentId(studentId);
            if (studentInfo != null && studentInfo.getUserId() != null)
            {
                // TODO: 可以添加检查：学生是否已有选题、申请等，根据业务决定是否允许删除

                // 删除用户角色关联
                userRoleMapper.deleteUserRoleByUserId(studentInfo.getUserId());
                // 删除系统用户
                userMapper.deleteUserById(studentInfo.getUserId());
            }
        }

        return studentInfoMapper.deleteStudentInfoByStudentIds(studentIds);
    }

    /**
     * 删除学生信息信息
     *
     * @param studentId 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentInfoByStudentId(Long studentId)
    {
        return studentInfoMapper.deleteStudentInfoByStudentId(studentId);
    }

    /**
     * 保存或更新学生信息
     * 如果该用户已有学生信息则更新，否则插入
     *
     * @param studentInfo 学生信息
     * @return 结果
     */
    @Override
    public int saveOrUpdateStudentInfo(StudentInfo studentInfo)
    {
        StudentInfo existingInfo = studentInfoMapper.selectStudentInfoByUserId(studentInfo.getUserId());
        if (existingInfo != null)
        {
            // 已存在，执行更新
            studentInfo.setStudentId(existingInfo.getStudentId());
            return updateStudentInfo(studentInfo);
        }
        else
        {
            // 不存在，执行插入
            return insertStudentInfo(studentInfo);
        }
    }

    // ==================== 新增：管理员功能 ====================

    /**
     * 新增学生信息并自动创建系统账号
     *
     * @param studentInfo 学生信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStudentInfoWithAccount(StudentInfo studentInfo)
    {
        // 1. 创建系统用户账号
        SysUser user = createUserAccount(
                studentInfo.getStudentNo(),
                studentInfo.getNickName(),
                studentInfo.getEmail()
        );



        // 插入用户
        int rows = userMapper.insertUser(user);
        if (rows > 0)
        {
            // 分配学生角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(101L);
            userRoleMapper.batchUserRole(java.util.Arrays.asList(userRole));

            // 2. 创建学生信息，关联用户ID
            studentInfo.setUserId(user.getUserId());
            studentInfo.setCreateTime(DateUtils.getNowDate());

            return studentInfoMapper.insertStudentInfo(studentInfo);
        }

        throw new ServiceException("创建学生账号失败");
    }

    /**
     * 校验学号是否唯一
     *
     * @param studentInfo 学生信息
     * @return 结果
     */
    @Override
    public boolean checkStudentNoUnique(StudentInfo studentInfo)
    {
        Long studentId = StringUtils.isNull(studentInfo.getStudentId()) ? -1L : studentInfo.getStudentId();
        StudentInfo info = studentInfoMapper.checkStudentNoUnique(studentInfo.getStudentNo());
        if (StringUtils.isNotNull(info) && info.getStudentId().longValue() != studentId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入学生信息数据
     *
     * @param studentList 学生信息数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importStudentInfo(List<StudentInfo> studentList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(studentList) || studentList.size() == 0)
        {
            throw new ServiceException("导入学生数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (StudentInfo student : studentList)
        {
            try
            {
                // 验证是否存在这个学生
                StudentInfo existStudent = studentInfoMapper.checkStudentNoUnique(student.getStudentNo());

                if (StringUtils.isNull(existStudent))
                {
                    // 新增学生
                    BeanValidators.validateWithException(validator, student);
                    student.setCreateBy(operName);
                    insertStudentInfoWithAccount(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学号 " + student.getStudentNo() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 更新学生
                    BeanValidators.validateWithException(validator, student);
                    student.setStudentId(existStudent.getStudentId());
                    student.setUserId(existStudent.getUserId());
                    student.setUpdateBy(operName);
                    updateStudentInfo(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学号 " + student.getStudentNo() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学号 " + student.getStudentNo() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学号 " + student.getStudentNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    /**
     * 重置学生账号密码
     *
     * @param studentId 学生ID
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public int resetStudentPassword(Long studentId, String operName)
    {
        StudentInfo studentInfo = studentInfoMapper.selectStudentInfoByStudentId(studentId);
        if (studentInfo == null || studentInfo.getUserId() == null)
        {
            throw new ServiceException("学生信息不存在或未关联系统账号");
        }

        // 重置密码为123456
        String newPassword = SecurityUtils.encryptPassword("123456");
        return userMapper.resetUserPwd(studentInfo.getUserId(), newPassword);
    }

    /**
     * 创建系统用户账号
     *
     * @param userName 用户名（工号/学号）
     * @param nickName 昵称前缀
     * @param email 邮箱
     * @return 用户对象
     */
    private SysUser createUserAccount(String userName, String nickName, String email)
    {
        // 检查用户名是否已存在
        SysUser existUser = userMapper.checkUserNameUnique(userName);
        if (existUser != null)
        {
            throw new ServiceException("用户名【" + userName + "】已存在，无法创建账号");
        }

        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setNickName(nickName);

        // 邮箱可以为空
        if (StringUtils.isNotEmpty(email))
        {
            user.setEmail(email);
        }

        // 设置默认密码：123456
        user.setPassword(SecurityUtils.encryptPassword("123456"));

        // 设置默认部门（可根据实际情况调整）
        user.setDeptId(103L); // 若依默认研发部门ID，请根据实际情况修改

        // 设置用户状态为正常
        user.setStatus("0");

        return user;
    }
}